﻿using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using Provausio.DependencyFinder.App.Wpf.Logic;
using Provausio.DependencyFinder.App.Wpf.Object.Domain;
using Provausio.DependencyFinder.App.Wpf.Object.ViewModel;

namespace Provausio.DependencyFinder.App.Wpf
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private DependencyFinderViewModel Context
        {
            get
            {
                return DataContext as DependencyFinderViewModel;
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            DataContext = new DependencyFinderViewModel();
        }

        private void BtnBrowseInputFilePath_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog {RestoreDirectory = true, Filter = "Dynamic Link Library (*.dll) | *.dll"};
            dialog.ShowDialog();

            if (!dialog.CheckFileExists) return;
            
            Context.DependentFilePath = Path.GetFileName(dialog.FileName);
            
        }

        private void BtnBrowseDirectory_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new FolderBrowserDialog();
            dialog.ShowDialog();
            if (Directory.Exists(dialog.SelectedPath))
            {
                Context.CheckDirectoryPath = dialog.SelectedPath;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(Context.CheckDirectoryPath) || string.IsNullOrEmpty(Context.DependentFilePath))
                return;

            var dependency = new Project(Context.DependentFilePath);
            var finder = new DependencySearcher();
            var results = finder.GetDependentProjects(Context.CheckDirectoryPath, dependency).ToList();

            var sb = new StringBuilder();
            sb.AppendFormat("Modifying the project \"{0}\" will affect the following {1} projects: \r\n\n", dependency.ProjectName, results.Count());

            foreach (var result in results)
            {
                sb.AppendFormat("{0} \r\n", result.ProjectName);
            }
            var message = finder.Searched > 0
                ? string.Format("{0} projects were analyzed", finder.Searched)
                : "No projects were found.";

            sb.AppendFormat("\r\n - {0} -", message);

            Context.SearchResults = sb.ToString();
        }
    }
}
